package com.yihu.wlyy.web.patient.medical;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yihu.wlyy.entity.patient.PatientMedicalRecords;
import com.yihu.wlyy.entity.patient.PatientMedicalRecordsItem;
import com.yihu.wlyy.service.app.medicines.MedicalRecordsService;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.web.BaseController;

/**
 * 患者端：病历夹控制类
 * @author George
 *
 */
@Controller
@RequestMapping(value = "/patient/medical/record")
public class PatientMedicalRecordController extends BaseController {

	@Autowired
	private MedicalRecordsService medicalRecordsService;

	/**
	 * 查询患者病历记录列表
	 * @param patient 患者标识
	 * @param id
	 * @param pagesize
	 * @return
	 */
	@RequestMapping(value = "list")
	@ResponseBody
	public String list(long id, int pagesize) {
		try {
			JSONArray array = new JSONArray();
			Page<PatientMedicalRecords> page = medicalRecordsService.findRecordsByPatient(getUID(), id, pagesize);
			for (PatientMedicalRecords temp : page) {
				if (temp == null) {
					continue;
				}
				JSONObject json = new JSONObject();
				// 记录ID
				json.put("id", temp.getId());
				// 记录标识
				json.put("code", temp.getCode());
				// 标题
				json.put("title", temp.getTitle());
				// 记录医生姓名
				json.put("doctorName", temp.getDoctorName());
				// 添加时间
				json.put("czrq", DateUtil.dateToStrLong(temp.getCzrq()));
				array.put(json);
			}
			return write(200, "查询成功！", "list", array);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败！");
		}
	}

	/**
	 * 查询病历记录明细
	 * @param record 病历记录标识
	 * @return
	 */
	@RequestMapping(value = "info")
	@ResponseBody
	public String info(String record) {
		try {
			JSONObject jsonObject = new JSONObject();
			JSONArray array = new JSONArray();
			// 查询主诉和图片信息
			PatientMedicalRecords pmr = medicalRecordsService.findRecordByCode(record);
			// 查询片段信息
			List<PatientMedicalRecordsItem> list = medicalRecordsService.findRecordItemByCode(record);
			for (PatientMedicalRecordsItem temp : list) {
				if (temp == null) {
					continue;
				}
				JSONObject json = new JSONObject();
				// 片段名称
				json.put("partName", temp.getPartName());
				// 片段内容
				json.put("content", temp.getContent());
				array.put(json);
			}
			String[] images = null;
			if (StringUtils.isNotEmpty(pmr.getImages())) {
				images = pmr.getImages().split(",");
			}
			// 主诉
			jsonObject.put("symptoms", pmr.getSymptoms());
			// 图片
			jsonObject.put("images", images);
			// 片段列表
			jsonObject.put("list", array);
			return write(200, "查询成功！", "data", jsonObject);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败！");
		}
	}

}
